const PMAT = 1,
	  VMAT = 2;

const MPI = 3.14159265,
	  RAG = MPI/180.0;

const FAH = 0.0955605391,
	  FAV = 0.0637070261;


function Scene()
{
	//
}

Scene.init = function()
{
	Scene.initView();

	//Mopengl.resManager = new RessourceManager();
	//Mopengl.resManager.allLoaded = Scene.initContent;

	//Scene.cctrl = Mopengl.resManager.addImage("./datas/ressources/cctrl.png");

    Scene.initContent();
}

Scene.initView = function()
{
	Scene.VMatrix = mat4.create();

	Scene.PMatrix = mat4.frustum(-FAH, FAH, -FAV, FAV,  0.1, 100.0);
	Scene.updateMatrix(PMAT);

	Scene.camera = new Camera([Scene.VMatrix, shaderProgram, "vMatrix"]); 
	Scene.camera.setOrientation(0.0, 0.0);
}

Scene.initContent = function()
{
//	Mopengl.resManager.createTexture(Scene.cctrl);
//	Mopengl.resManager.createPlane(Scene.cctrl);


	Scene.objManager = new WavefrontManager();

	WavefrontManager.imagesReady = function()
	{
		Scene.objManager.finish(Scene.draw);
	}

	var wavefrontAdder = function(xhr)
		{			
			var filedata = xhr.responseText;
			var wavefrontFiles = filedata.split(" ");

			for(var i = 0; i < wavefrontFiles.length; i++)
			{
				var fname = wavefrontFiles[i];
				Scene.objManager.add("./datas/wavefronts/"+fname+".obj");
				Scene.objManager.addImage("./datas/textures/"+fname+".png");
			}
		}

	getDoc("./php/getObjFileNames.php", wavefrontAdder);
}

Scene.draw = function()
{	
	gl.clearColor(1.0, 1.0, 1.0, 1.0);

	gl.clear( gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);

	if(Mopengl.mouse.boutonState == "down")
	{
		var mx = Mopengl.mouse.getPosition().x - Mopengl.mouse.positionOnDown.x;
		var my = Mopengl.mouse.getPosition().y - Mopengl.mouse.positionOnDown.y;

		if(mx!=undefined && my != undefined)
		{
			Scene.camera.cumulOrientation(
				-RAG*parseInt(mx * 20.0/Mopengl.canvas.offsetWidth),
				RAG*parseInt(my * 20.0/Mopengl.canvas.offsetHeight)
			);
		}
	}

	Scene.camera.setPosition(0.0, -3.0, -6.0);
	Scene.updateMatrix(VMAT);

	for(var i = 0; i < Scene.objManager.stack.length; i++)
	{
		Scene.objManager.stack[i].draw();
	}

//	Mopengl.resManager.restore2D(Scene.VMatrix);
//	Mopengl.resManager.show(Scene.cctrl);
	
	window.setTimeout(Scene.draw, 1000/24);
}

Scene.updateMatrix = function(mIdentifier)
{
	if(mIdentifier & 1)
	{
		var up = gl.getUniformLocation(shaderProgram, "pMatrix");
		gl.uniformMatrix4fv(up, false, Scene.PMatrix);
	}

	if(mIdentifier & 2)
	{
		mat4.identity(Scene.VMatrix);
		Scene.camera.updateTranformation();
	}
}
